<template>
  <UtilForm ref="addFormRef" :labels="formLabels" :config="formconfig" @emit-util-form="echoFormHandler">
    <el-button @click="handleCloseDialog" plain>取消</el-button>
    <el-button type="success" @click="handleSubmit">添加</el-button>
  </UtilForm>
</template>

<script setup>
import UtilForm from '../../components/UtilForm.vue';
import { ref, reactive, watch, getCurrentInstance } from 'vue';
import { ElMessage } from 'element-plus';

const { proxy: { $axios, $store } } = getCurrentInstance();

const addFormRef = ref();
const emit = defineEmits(['emit-add-user']);
const props = defineProps({
  status: Boolean
});

const state = reactive({
  form: {}
});
const formconfig = reactive({
  reset: true,
  clearable: false
});

const formLabels = reactive([
  { field: 'username', label: '用户名', labelType: 'text', required: true },
  { field: 'fullname', label: '姓名', labelType: 'text', required: true },
  {
    field: 'gender',
    label: '性别',
    labelType: 'radio',
    dict: getEnumAllMembers('gender'),
    required: true
  },
  {
    field: 'role',
    label: '角色',
    labelType: 'checkbox',
    dict: getEnumAllMembers('role'),
    required: true
  },
  { field: 'age', label: '年龄', labelType: 'inputNumber', min: 0, max: 122, required: true },
  // { field: 'avatar', label: '头像', labelType: 'upload' },
]);

function getEnumAllMembers(key) {
  const statusDef = $store.getters['enums/getEnums'](key);
  return statusDef.getAllMembers()
}

function handleCloseDialog(refresh = false) {
  formconfig.clearable = true;
  emit('emit-add-user', { status: false, refresh });
}

async function handleSubmit() {
  const path = '/api/user/add';
  const params = formaterParams(state.form);

  try {
    const { code, data, message } = await $axios.post(path, params);

    if (code === 200 && data.id) {
      ElMessage.success(message);
      handleCloseDialog(false);
    }
  } catch (err) {
    console.error('添加用户失败:', err);
  } finally {
    // 关闭页面
    // 清空表单
    // state.loading = false;
  }
}

function echoFormHandler(data) {
  state.form = data.form;
}

function formaterParams(data) {
  let role = 0;
  const roles = data.role || [];

  if (roles.length) {
    role = roles.reduce((t, c) => t | c);
  }
  return { ...data, role };
}

watch(() => props.status, s => {
  formconfig.clearable = s;
});
</script>